<?php
class mcz_Playlist extends mcz_Object
{
	protected $fields = array(
		'id'      => array('cast' => 'integer'),
		'title'   => array('cast' => 'string',
						   'notblank' => true),
		'user_id' => array('cast' => 'integer',
						   'notblank' => true)
	);

	public function add(array $items)
	{
		if(empty($this->id))
		{
			$this->save();
		}
		foreach($items as $item)
		{
			$assoc = new mcz_PlaylistTune();
			$assoc->playlist_id = $this->id;
			$assoc->tune_id = $item;
			$assoc->save();
		}
	}

	public function findItems()
	{
		$tunes = array();
		$res = mcz_DB::getInstance()->fetch('tune_id from mcz_PlaylistTune where playlist_id = ?', array($this->id));
		foreach($res as $item)
		{
			$tune = mcz_Tune::find($item['tune_id']);
			if($tune)
			{
				$tunes[] = $tune;
			}
		}
		return $tunes;
	}

	public static function findAllFromUserLogin($login)
	{
		$pls = array();
		$user = mcz_User::findOneByLogin($login);
		$pls = self::hydrate(get_class(),
							 self::dbh()
								->fetch('* from ' . get_class()
										. ' where user_id=?',
										array($user->id)));
		return $pls;
	}

	public static function findAll()
	{
		$pls = array();
		$pls = self::hydrate(get_class(),self::dbh()->fetch('* from mcz_Playlist where user_id=' . $_SESSION['obj']->id . ' order by title'));
		return $pls;
	}

	public static function find($id)
	{
		$res = self::dbh()->fetch('* from ' . get_class() . ' where id=?',
								  array((int)$id));
		if($res)
		{
			return new mcz_Playlist($res[0]);
		}
		return false;
	}
}